package com.michale.admin.mqtt.service;

import com.michale.common.utils.String.StringUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.michale.common.constants.MqttConstant.MQTT_INPUT_CHANNEL;
import static com.michale.common.constants.MqttConstant.MQTT_RECEIVED_TOPIC;


/**
 * @author Michale
 * @apiNote 接收到的数据
 */
@Slf4j
@Api(tags = "接收到的数据")
@Component
public class MqttMessage implements MessageHandler {

    /**
     * Handle the given message.
     *
     * @param message the message to be handled
     * @throws MessagingException if the handler failed to process the message
     */
    @Override
    @ServiceActivator(inputChannel = MQTT_INPUT_CHANNEL)
    public void handleMessage(Message<?> message) throws MessagingException {
        String topic = Objects.requireNonNull(message.getHeaders().get(MQTT_RECEIVED_TOPIC)).toString();
        String payload = message.getPayload().toString();
        log.info("订阅的主题:{} 发送的内容:{}", topic, payload);
        checkTopic(topic, payload);
    }

    /**
     * 模拟硬件设备
     *
     * @param topic   订阅的主题
     * @param payload 消息报文
     */
    private void checkTopic(String topic, String payload) {
        if (StringUtils.inStringIgnoreCase(topic, "michale/furniture/led")) {
            extracted(payload, "客厅灯已打开", "客厅灯已关闭");
        } else if ((StringUtils.inStringIgnoreCase(topic, "michale/furniture/tv"))) {
            extracted(payload, "电视已打开", "电视已关闭");
        }
    }

    /**
     * 打印日志
     *
     * @param payload  消息报文
     * @param megTrue  正确信息
     * @param msgFalse 错误信息
     */
    private void extracted(String payload, String megTrue, String msgFalse) {
        if (StringUtils.inStringIgnoreCase(payload, "1")) {
            log.info(megTrue);
        } else {
            log.info(msgFalse);
        }
    }
}
